package com.example.demo.test.alc.login;

import com.example.demo.socket.WebSocketServer;
import com.example.demo.test.selenium.SeleniumHelper;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

@Component
public class AccountLoginBySelf extends SeleniumHelper implements AccountLoginStrategy {
    @Override
    public void login() {
        String loginURL = "";
        try {
            WebSocketServer.screenInfoMsg("======================loginAccount======================");
            String LoginUserInput = "UserID";
            String loginPasswordInput = "Password";
            String myUserId = "978880162@qq.com";
            String myPassword = "1q2w3e4r";
            int sleepMillis = 500;

            WebSocketServer.screenInfoMsg("登录测试开始 打开登录地址: %s", loginURL);
            driver.get(loginURL);

            WebSocketServer.screenInfoMsg(String.format("获取页面元素 %s,等待成功后继续往下执行.", LoginUserInput));
            wait.until(ExpectedConditions.presenceOfElementLocated(By.id(LoginUserInput)));

            Thread.sleep(sleepMillis);

            WebElement userID = driver.findElement(By.id(LoginUserInput));
            WebSocketServer.screenInfoMsg("清空表单,开始输入[%s]: %s ", LoginUserInput, myUserId);
            userID.clear();
            userID.sendKeys(myUserId);

            Thread.sleep(sleepMillis);

            WebElement password = driver.findElement(By.id(loginPasswordInput));
            WebSocketServer.screenInfoMsg("清空 并开始输入[%s]: %s ", loginPasswordInput, myPassword);
            password.clear();
            password.sendKeys(myPassword);

            Thread.sleep(sleepMillis);
            WebSocketServer.screenInfoMsg("点击登录");
            driver.findElement(By.id("btnsignin")).click();
            waitByPath("//a[@href='/us/en/myprofile']");
        } catch (Exception e) {
            e.printStackTrace();
            WebSocketServer.screenInfoMsg("登录异常,错误消息: %s", e.getMessage());
            String filename = "jjj" + ".png";
            //定义文件存放目录
            String Directory = "C:\\Users\\zhangxianwen\\Desktop\\";
            File sourceFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            try {
                FileUtils.copyFile(sourceFile, new File(Directory + filename));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

}
